package com.zut.controller;

import com.alibaba.fastjson.JSONObject;
import com.zut.domain.User;
import com.zut.service.UserService;
import com.zut.service.impl.ThingsBoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 调用auth.code2Session接口，换取openid等信息
 **/

@RestController
@RequestMapping("/login")
public class WeChatController {



    @Autowired
    private UserService userService;


    String AppId = "wx707022182f054248";  //公众平台自己的appId
    String AppSecret = "c18ac151e41a0ee2016999650adee590";  //AppSecret

    @GetMapping("/login")
    public Map<String, User> wxLogin(@RequestParam("code") String code) throws Exception {
        Map<String, User> map = new HashMap<String, User>();
        System.out.println(code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + AppId +
                "&secret=" + AppSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //利用spring原生http请求工具对接口进行请求
        String jsonData = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        //请求返回的是Json类型的数据 所以我们需要用到fastjson
        System.out.println("jsonData");
        System.out.println(jsonData);
        System.out.println("jsonData");
        System.out.println(jsonObject);
        String openid = jsonObject.getString("openid");
        System.out.println(openid);
        User user = userService.selectOneUser(openid);
        System.out.println(user);
        if (user == null) {
            user = new User();
            user.setId(openid);
            map.put("false", user);
        } else {
            map.put("true", user);
        }
        return map;
    }

    @PostMapping("/register")
    public boolean getUserStatus(@RequestBody User user) throws Exception {
        return userService.insert(user);
    }



}


